<?php


namespace app\api\controller;
use app\BaseController;
use app\common\ArrayFunction;
use app\common\JSSDK;

use app\common\OssTool;
use app\model\BrowseRecords;
use app\model\Collect;
use app\model\HistorySearch;
use app\model\Member;
use app\model\VisitCity;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Request;
use think\facade\Db;
use think\facade\View;
use think\facade\Route;
use think\facade\Cookie;
use function Symfony\Component\Translation\t;

class Base extends BaseController
{
    protected $where = [];
    protected $order = ['id'=>'desc']; //排序
    protected $model; //模型引入
    protected $list_rows = 100; //分页数量
    protected $status = ['status'=>1]; //开启状态
    protected $index_status = ['index_status'=>1]; //开启状态
    protected $msg; //提示信息
    protected $field = [];
    protected $without_field = [];
    protected $append = [];
    protected $hidden = [];
    protected $hidden_view = [];
    protected $without_field_view = [];
    protected $view = [];
    protected $index = [];
    protected $all = [];

    public function initialize()
    {

    }

    /**
     * @param $name
     * @param $arguments
     * @return array
     * 魔术方法 action
     */
    public function __call($name, $arguments)
    {
        return ['code'=> 400 ,'msg'=>'当前方法不存在:'.$name];
    }

    public function __get($name)
    {
        // TODO: Implement __get() method.
        echo 1;
    }

    /**
     * @param Request $request
     * @return array
     * 有分页列表
     */
    public function index(Request $request)
    {

        try {
            $data = $this->model::withSearch(array_keys($request->data), $request->data)
                ->field($this->index)
//                ->withoutField($this->without_field)
                ->where($this->status)
                ->where($this->where)
                ->order($this->order)
                ->paginate($this->list_rows);
            if($this->append){
                $data->append($this->append);
            }
            if($this->hidden){
                $data->hidden($this->hidden);
            }
            return ['code' => 200, 'msg' => $this->msg . '列表', 'data' => $data];
        } catch (\Exception $e) {
            return ['code'=>$e->getCode(),'msg'=>$e->getMessage(),'line'=>$e->getTrace()];
        }
    }

    /*
     * 无分页列表
     */
    public function all(Request $request)
    {
            $data = $this->model::withSearch(array_keys($request->param),$request->param)

                ->field($this->all)
                ->where($this->status)
                ->where($this->where)
                ->order($this->order)
                ->select();
        if ($this->append) {
            $data->append($this->append);
        }
        if ($this->hidden) {
            $data->hidden($this->hidden);
        }
        return ['code' => 200, 'msg' => $this->msg.'列表', 'data' => $data];
    }

    public function view(Request $request)
    {
        try {

            $data = $this->model::where($this->status)->field($this->view)->find($request->id);
            if (isset($data['visitor_num'])) { //存在这个字段和empty不一样
                $data->where('id',$request->id)->inc('visitor_num')->update();
            }
            if ($this->append) {
                $data->append($this->append);
            }
            if ($this->hidden) {
                $data->hidden($this->hidden);
            }


            return ['code' => 200, 'msg' => $this->msg . '详情', 'data' => $data];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'msg' => $e->getMessage(),];
        }
    }

    public function html(Request $request)
    {
        $request->field = !empty($request->field) ? $request->field : 'content';
        $data = $this->model::where('id', $request->id)->value($request->field);
        $content = '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">';
        $content .= '<style>*{margin:0;padding: 0} img {vertical-align:middle; width:auto; max-width:100%!important;} </style>';
        $content .= $data;
        return response($content);
    }

    public function json(Request $request)
    {
        $data = $this->model::where('id', $request->id)->value($request->value);
        $data = str_replace('src="', 'src="' . $request->domain(), $data);
        //$dataInfo['detail_html'] = str_replace('<img', '<img style="display:block;"', $dataInfo['detail_html']);
        return $data;
    }

    /*
     * 添加
     */
    public function create(Request $request)
    {
        try {
            $ret = $this->model::create($request->data);
            return ['code' => 200, 'msg' => $this->msg . '创建成功', 'data' => $ret];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    /*
     * 修改
     */
    public function update(Request $request)
    {
        try {
            $info = $this->model::find($request->id);
            $ret = $info->save($request->data);
            if ($ret !== false) {
                return ['code' => 200, 'msg' => $this->msg . '修改成功','data'=> $request->param];
            }
            return ['code' => 200, 'msg' => '失败'];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    /*
     * 删除
     */
    public function destory(Request $request)
    {

        $ret = $this->model::where('id','in',$request->id)->update(['delete_time' => date('Y-m-d H:i:s')]);
        if ($ret) return ['code' => 200, 'msg' => $this->msg . '删除成功,ID=' . $request->id,'count'=>$ret];
        return ['code' => 400, 'msg' => '失败'];
    }

    /*
     * 单一删除
     */
    public function destory_ones(Request $request)
    {
        $ret = $this->model::destroy($request->id);
        if ($ret) return ['code' => 200, 'msg' => $this->msg . '删除成功,ID=' . $request->id];
        return ['code' => 400, 'msg' => '失败'];
    }




    /**
     * @param Request $request
     * @return array
     * 多级分类查询
     */
    public function level(Request $request)
    {
        $data = $this->model::withSearch(array_keys($request->data), $request->data)
            ->where($this->status)
            ->order($this->order)->select();
        return ['code' => 200, 'msg' => $this->msg . '层级查询', 'data' => $data];
    }

    /*
     * 全部层级
     * 状态关闭或者数量0去除
     */

    public function level_all()
    {
        $data =  $this->model::where('parent_id',0)->where($this->status)->order($this->order)->select();
        $ret_data = [];
        foreach ($data as $k=> $v){
            $son = $this->model::where('parent_id',$v['id'])->where($this->status)->order($this->order)->select();
            $v['son'] = $son;
            if(!$son->isEmpty()){
                $ret_data[] = $v;
            }
        }
        return ['code' => 200, 'msg' => $this->msg.'所有层级', 'data' => $ret_data];
    }

    public function upload_one()
    {
        $model = config('app.upload_mode');

        if(true){

            return ['code' => 200,'msg'=>'图片上传成功','img' => uploadOne('file')];
        }
        if($model == 2){
            halt(134);
            return ['code' => 200,'msg'=>'图片上传成功','img' => (new OssTool())->upload_one()];
        }

//        $module = app('http')->getName();
//        $file = Request::file('single_pic');
//        $param = Request::param();
//        if (Request::action() == 'batch_create') {
//            $savename = \think\facade\Filesystem::disk('public')->putFileAs($module, Request::file('multi_pic'), $file->getOriginalName());
//            return json_encode(['code' => 0, 'img' => $savename]);
//        } else {
//            if (!empty($param['rule'])) {
//                return json_encode(['code' => 0, 'img' => uploadOneOrigin('file')]);
//            } else {
//                return json(['code' => 200,'msg'=>'图片上传成功', 'data' => uploadOne('single_pic')]);
//            }
//
//        }
    }

    public function upload_many()
    {
        // 获取表单上传文件

        $files = request()->file('file');
        $savename = [];
        foreach ($files as $file) {
            $savename[] = request()->domain().'/storage/'.\think\facade\Filesystem::disk('public')->putFile('', $file);;
        }
        return ['code' => 200,'msg'=>'多个图片上传成功', 'url' => implode(',',$savename),'arg'=>$savename];
    }



    public function upload_member()
    {

        $module = app('http')->getName();
        $file = Request::file('single_pic');
        $headimgrul = uploadOne('single_pic');
        $ret = (new \app\model\Member())->where('id',Cookie::get('member_id'))->update(['headimgurl'=>$headimgrul]);

        $param = Request::param();
        if (Request::action() == 'batch_create') {
            $savename = \think\facade\Filesystem::disk('public')->putFileAs($module, Request::file('multi_pic'), $file->getOriginalName());
            return json_encode(['code' => 0, 'img' => $savename]);
        } else {
            if (!empty($param['rule'])) {
                return json_encode(['code' => 0, 'img' => uploadOneOrigin('file_data')]);
            } else {
                return json(['code' => 0, 'img' => uploadOne('single_pic')]);
            }

        }
    }


    /**
     * @param Request $request
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * 收藏切换
     */
    public function tab_collect(Request $request)
    {
        try {
            $collect = Collect::where(
                [
                    ['member_id', '=', $request->member_id],
                    ['controller', '=', $request->controller],
                    ['view_id', '=', $request->id],
                ]
            )->find();

            if (!empty($collect)) {
                $ret = $collect->delete();
                if ($ret) {
                    return ['code' => 202, 'msg' => '取消收藏'];
                }
            } else {
                $args =[
                    'EquipmentSafe'=>'设备安拆',
                    'EquipmentRepair'=>'设备快修',
                    'SecondEquipmentSale'=>'二手设备出售',
                    'SecondEquipmentBuy'=>'二手设备求购',
                    'PartsShop' => '配件商城商家',
                    'PartsBuyer' => '配件商城买家',
                    'Construction' => '建筑招工',
                    'EquipmentRent' => '设备租赁求租',
                    'EquipmentSale' => '设备租赁出售',
                    'Position' => '求职招聘招聘',
                    'Job' => '求职招聘求职'
                    ];
                $ret = Collect::create(['member_id' => $request->member_id, 'controller' => $request->controller,'controller_name'=> $args[$request->controller], 'view_id' => $request->id]);
                if ($ret) {
                    return ['code' => 201, 'msg' => '收藏成功'];
                }
            }
            return ['code' => 400, 'msg' => '失败'];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }




    /**
     * @param $table
     * @param $id
     * @return mixed
     * 查询一条数据
     */
    public function find($table,$id)
    {
        $class = 'app\model\\' . $table;
        $data = (new $class)->find($id);
        return $data;
    }

    /**
     * @param $table
     * @param $id
     * @param $field
     * @return mixed
     * 查询单个字段数据;
     */
    public function value($table, $id, $field)
    {
        $class = 'app\model\\' . $table;
        $data = (new $class)->where('id', $id)->value($field);
        return $data;
    }

    public function select($table, $sort = true)
    {
        $class = 'app\model\\' . $table;
        if ($sort == true) {
            $data = (new $class)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        } else {
            $data = (new $class)->order(['id' => 'desc'])->select();
        }
        return $data;
    }

    /**
     * 省市区3级联动
     */
    public function prov_city_area()
    {
        $prov = Db::name('cn_prov')->field('code,name')->select()->toArray();
        foreach ($prov as &$v) {
            $v['city'] = Db::name('cn_city')->field('code,name')->where('pcode', $v['code'])->select()->toArray();
            foreach ($v['city'] as &$vv){
               // $vv['area'] = Db::name('cn_area')->field('name')->where('pcode', $vv['code'])->select();
            }
        }
        return json(['code' => 200, 'message' => '省市区', 'data' => $prov]);
    }
    /**
     * 市区2级联动
     */
    public function city_area()
    {
        $city = Db::name('cn_city')->field('code,name')->select()->toArray();
        foreach ($city as &$vv) {
            $vv['list'] = Db::name('cn_area')->field('name')->where('pcode', $vv['name'])->select();
        }
        return ['code' => 200, 'message' => '省市区', 'data' => $city];
    }

    /**
     * 城市A_Z
     */
    public function city_az(Request $request)
    {
        $letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        $letters = DB::name('cn_city')->order(['description' => 'asc'])->group('description')->column('description');
        $data = [];
        foreach ($letters as $k => $v) {
            $data[$k]['letters'] = $v;
            $data[$k]['list'] = DB::name('cn_city')->field(['name', 'description'])->where('description', $v)->order(['description' => 'asc'])->select();
        }
        $hot_city = explode(' ',cache('web_hot_city'));
        $visit_city = VisitCity::where('member_id',$request->member_id)->order(['id'=>'desc'])->limit(4)->select();
        return ['code' => 200, 'msg' => '城市AZ排序', 'hot_city'=>$hot_city,'visit_city'=> $visit_city,'data' => $data];
    }

    /**
     * @param Request $request
     * 历史搜索
     */
    public function history_search(Request $request)
    {
        $data = HistorySearch::where('member_id', $request->member_id)->limit(15)->select();
        $hot_data = config('web_config.web_search');
        $hot_data = explode(' ',$hot_data);
        return ['code' => 200, 'msg' => '历史搜索', 'data' => $data,'hot_data'=>$hot_data];
    }

    /*
     * 会员历史搜索添加数据
     */
    public function history_create(Request $request)
    {
       $history = HistorySearch::where([['member_id','=',$request->member_id],['title','=',$request->title]])->find();
       if(!empty($history)){
           $history->delete();
       }
        $data = HistorySearch::create(['member_id'=>$request->member_id,'title'=> $request->title]);
        return ['code' => 200, 'msg' => '历史搜索', 'data' => $data];
    }

    /**
     * @param Request $request
     * @return array
     * @throws \Exception
     * 删除清理纪录
     */
    public function history_clear(Request $request)
    {
        $ret = HistorySearch::where('member_id',$request->member_id)->delete();
        if($ret){
            return ['code' => 200, 'msg' => '历史搜索清空成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }

    public function create_city(Request $request)
    {
        $browse_records = VisitCity::where('member_id', $request->member_id)
            ->where('title', $request->title)->delete();
        VisitCity::create([
            'title' => $request->title,
            'member_id' => $request->member_id,
        ]);
        return ['code' => 200, 'msg' => '最近城市添加成功'];
    }


    public function get_months()
    {
        $months = get_months();
        $first_month = $months[0];
        return ['code' => 200, 'msg' => '获取最近月份', 'data' => $months,'first_month'=>$first_month];
    }







}